Skip to content

Support attr_reader/attr_writer/attr_accessor in singleton classes#463

Merged
sinsoku merged 1 commit into
ruby:masterfrom
pvcresin:support-eigenclass-attr
Jun 22, 2026
Merged

Support attr_reader/attr_writer/attr_accessor in singleton classes#463
sinsoku merged 1 commit into
ruby:masterfrom
pvcresin:support-eigenclass-attr

Conversation

@pvcresin

Copy link
Copy Markdown
Contributor

Summary

attr_reader / attr_writer / attr_accessor written inside a singleton class (class << self) were treated as instance methods:

class C
  class << self
    attr_accessor :age
  end
end

was inferred as def age / def age= instead of def self.age / def self.age=.

Changes

  • Detect the metaclass scope in the three attr meta nodes — the same lenv.cref.scope_level == :metaclass check DefNode already uses — and define the accessors and their backing ivar on the singleton. This also covers class << SomeConstant.
  • Promote scenario/known-issues/eigenclass-attr.rb to scenario/class/.

All 433 tests pass (bundle exec rake test).

@pvcresin pvcresin force-pushed the support-eigenclass-attr branch from 6e30078 to fcec0a8 Compare June 21, 2026 15:32
`attr_reader`, `attr_writer`, and `attr_accessor` written inside a
singleton class (e.g. `class << self`) were always treated as instance
methods, so

    class C
      class << self
        attr_accessor :age
      end
    end

was dumped as `def age` / `def age=` instead of `def self.age` /
`def self.age=`.

The three attr meta nodes ignored the enclosing scope and hardcoded
`false` for the singleton flag when resolving the backing ivar and
defining the methods. Detect the metaclass scope the same way `DefNode`
does (`lenv.cref.scope_level == :metaclass`) and thread it through, so
the accessors and their ivar are defined on the singleton. This also
covers `class << SomeConstant`.

Promote scenario/known-issues/eigenclass-attr.rb to scenario/class/.

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
@pvcresin pvcresin force-pushed the support-eigenclass-attr branch from fcec0a8 to 8d282ed Compare June 21, 2026 15:37
@sinsoku sinsoku merged commit e7cf8c1 into ruby:master Jun 22, 2026
6 checks passed
@pvcresin pvcresin deleted the support-eigenclass-attr branch June 22, 2026 11:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants